package com.tanjun.mallservice.web.biz.impl;

import com.tanjun.common.utils.ConvertUntil;
import com.tanjun.mallservice.apiservice.request.cate.CateTypeVo;
import com.tanjun.mallservice.apiservice.response.cate.CateTreeDto;
import com.tanjun.mallservice.web.biz.MallCateBiz;
import com.tanjun.mallservice.web.orm.entity.MallCate;
import com.tanjun.mallservice.web.service.MallCateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MallCateBizImpl implements MallCateBiz {
    @Autowired
    private MallCateService mallCateService;

    @Override
    @Cacheable(value ="listTreeCateByCateType",key = "#paramVo.cateType")
    public List<CateTreeDto> listTreeCateByCateType(CateTypeVo paramVo) {
        List<MallCate> list = mallCateService.listCateByType(paramVo.getCateType());
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        List<CateTreeDto> listRe= list.stream().filter(t->t.getCateLevel()==1)
                .sorted(Comparator.comparingInt(MallCate::getSno))
                .map(t->ConvertUntil.convert(t,CateTreeDto.class))
                .collect(Collectors.toList());
        listRe.forEach(d->getChildrenCate(d,list));
        return listRe;

    }

    /**
     * 通过递归获取所有的
     * @param cateTreeDto
     * @param listIn
     */

    private void getChildrenCate(CateTreeDto cateTreeDto,List<MallCate> listIn){
      List<CateTreeDto> listChildren= listIn.stream().filter(t-> Objects.equals(t.getCateParentId(), cateTreeDto.getCateId()))
                .sorted(Comparator.comparingInt(MallCate::getSno))
                .map(t-> ConvertUntil.convert(t,CateTreeDto.class))
                .collect(Collectors.toList());
      cateTreeDto.setListChildren(listChildren);
      if(!CollectionUtils.isEmpty(listChildren)){
          listChildren.forEach(t->getChildrenCate(t,listIn));
      }
    }




}
